package com.zkb.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zkb.config.constant.K3Type;
import com.zkb.config.k3cloud.K3clopudProperties;
import com.zkb.service.IKService;
import jakarta.annotation.Resource;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

public class IKServiceImpl implements IKService {

    private static String CookieVal = null;

    @Resource
    K3clopudProperties k3clopudProperties;
    @Override
    public JSONObject save(String formId, String content) throws Exception {
        this.Login();
        return Invoke(K3Type.SAVE, formId, content);
    }

    @Override
    public JSONObject view(String formId, String content) throws Exception {
        this.Login();
        return Invoke(K3Type.VIEW, formId, content);
    }

    @Override
    public JSONObject submit(String formId, String content) throws Exception {
        this.Login();
        return Invoke(K3Type.SUBMIT, formId, content);
    }

    @Override
    public JSONObject statusConvert(String formId, String content) throws Exception {
        this.Login();
        return Invoke(K3Type.STATUSCONVERT, formId, content);
    }

    @Override
    public JSONObject audit(String formId, String content) throws Exception {
        this.Login();
        return Invoke(K3Type.AUDIT, formId, content);
    }

    @Override
    public JSONObject unAudit(String formId, String content) throws Exception {
        this.Login();
        return Invoke(K3Type.UNAUDIT, formId, content);
    }
    @Override
    public boolean Login() throws Exception {
        boolean bResult = false;
        JSONArray jParas = new JSONArray();
        jParas.add(k3clopudProperties.dbId);// 帐套Id
        jParas.add(k3clopudProperties.name);// 用户名
        jParas.add(k3clopudProperties.pwd);// 密码
        jParas.add(k3clopudProperties.lang);// 语言
        HttpURLConnection connection = initUrlConn(K3Type.LOGIN, jParas);
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("Set-Cookie")) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    CookieVal = tempCookieVal;
                    break;
                }
            }
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream(),"utf-8"));
        String line;
        while ((line = reader.readLine()) != null) {
           String sResult = new String(line.getBytes("utf-8"), "utf-8");
             System.out.println(sResult);
            bResult = line.contains("LoginResultType");
        }
        reader.close();
        connection.disconnect();
        return bResult;
    }
    private JSONObject Invoke(String type, String formId, String content) throws Exception {
        String sResult = "";
        JSONArray jParas = new JSONArray();
        jParas.add(formId);
        jParas.add(content);

        HttpURLConnection connectionInvoke = initUrlConn(type,jParas);

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream(), "utf-8"));
        String line;
        System.out.println("==============================================");
        System.out.println("Contents of post request");
        System.out.println("==============================================");
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes("utf-8"), "utf-8");
//             System.out.println(sResult);
        }
        System.out.println("==============================================");
        System.out.println("Contents of post request ends");
        System.out.println("==============================================");
        reader.close();
        connectionInvoke.disconnect();
        return JSONObject.parseObject(sResult);
    }



    private HttpURLConnection initUrlConn(String type,JSONArray paras)
            throws Exception {
        URL postUrl = new URL(k3clopudProperties.POST_K3CloudURL.concat(type));
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        if (CookieVal != null) {
            connection.setRequestProperty("Cookie", CookieVal);
        }
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());

        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();

        JSONObject jObj = new JSONObject();

        jObj.put("format", 1);
        jObj.put("useragent", "ApiClient");
        jObj.put("rid", hashCode);
        jObj.put("parameters", chinaToUnicode(paras.toString()));
        jObj.put("timestamp", new Date().toString());
        jObj.put("v", "1.0");

        out.writeBytes(jObj.toString());
        out.flush();
        out.close();

        return connection;
    }
    /**
     * 把中文转成Unicode码
     *
     * @param str
     * @return
     */
    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }
}
